package com.tuling.code.algorithm.loadbalance.simple;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 加权随机（Weight Random）法
 * @author javaw
 */
public class WeightRandom implements LoadBlanceStragety {

	@Override
	public String getServer(String src) {
		Map<String, Integer> serverMap = new HashMap<>();
		serverMap.putAll(IpMap.serverWeightMap);

		Iterator<String> it = serverMap.keySet().iterator();

		List<String> serverList = new ArrayList<>();

		while (it.hasNext()) {
			String server = it.next();
			int weight = serverMap.get(server);
			for (int i = 0; i < weight; i++) {
				serverList.add(server);
			}
		}

		java.util.Random random = new java.util.Random();

		int randomPos = random.nextInt(serverList.size());
		
		String server = serverList.get(randomPos);

		System.out.println("randomPos=" + randomPos + " , weight = " + serverMap.get(server) + " , serverIp = " + server);
		return server;
	}

}
